<template>
    <div class="list-component">
        <el-form class="search-bar" :inline="true" :model="filter" ref="filter">
            <el-form-item label="姓名" prop="name">
                <el-input v-model="filter.name" placeholder="请输入姓名"></el-input>
            </el-form-item>
            <el-form-item label="账号" prop="account">
                <el-input v-model="filter.account" placeholder="请输入账号"></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="phone">
                <el-input v-model="filter.phone" placeholder="请输入电话"></el-input>
            </el-form-item>
            <el-form-item label="状态" prop="status" v-show="false">
                <el-select v-model="filter.status" placeholder="请选择状态">
                    <el-option label="全部" value=""></el-option>
                    <el-option label="正常" value="0"></el-option>
                    <el-option label="冻结" value="1"></el-option>
                </el-select>
            </el-form-item>
             <el-form-item class="filter-button">
                <el-button type="primary" size="small" @click="getList(1)">查询</el-button>
                <el-button type="primary" size="small" @click="resetForm">清空</el-button>
            </el-form-item>
        </el-form>
        <div class="list">
            <div class="button-bar">
                <el-button class="btn" type="primary" size="mini" icon="el-icon-plus" @click="onAdd" v-pms="'userEdit'">新建</el-button>
                <!-- <el-button class="btn" type="danger" size="mini" icon="el-icon-delete" @click="onDelete" >删除</el-button>
                <el-button class="btn" type="warning" size="mini" icon="el-icon-refresh-right" @click="onResetPsw" title="点击重置密码为123456">重置密码</el-button> -->
            </div>
            <div class="data">
                <el-table :data="listData.data"  stripe ref="listData" @select-all="onSelectAll" @select="onSelect" v-height="'auto'" >
                    <el-table-column type="selection"  align="center"   width="50" v-if="false"></el-table-column>
                    <el-table-column type="index" label="序号" align="center" prop="index" width="60px" >
                        <div slot-scope="scope">
                            {{(listData.pageNum - 1) * listData.pageSize + 1 + scope.$index }}
                        </div>
                    </el-table-column>
                    <el-table-column label="姓名" prop="name" align="center" width="">
                        <slot slot-scope="scope">
                            <span :title="scope.row.name">{{scope.row.name}}</span>
                        </slot>
                    </el-table-column>
                    <el-table-column label="账号" prop="account" align="center" width="">
                        <slot slot-scope="scope">
                            <span :title="scope.row.account">{{scope.row.account}}</span>
                        </slot>
                    </el-table-column>
                    <el-table-column label="角色" prop="roleName" align="center"  width="">
                        <slot slot-scope="scope">
                            <span :title="scope.row.roleName">{{scope.row.roleName}}</span>
                        </slot>
                    </el-table-column>
                    <el-table-column label="电话" prop="phone" align="center" width="">
                        <slot slot-scope="scope">
                            <span :title="scope.row.phone">{{scope.row.phone}}</span>
                        </slot>
                    </el-table-column>
                    <el-table-column label="创建时间" prop="createTime"  align="center" width="">
                        <slot slot-scope="scope">
                            <span :title="scope.row.createTime">{{scope.row.createTime}}</span>
                        </slot>
                    </el-table-column>
                    <el-table-column label="状态" prop="statusName" align="center" width="">
                        <slot slot-scope="scope">
                            <span :title="scope.row.statusName">{{scope.row.statusName}}</span>
                        </slot>
                    </el-table-column>
                    <el-table-column label="操作"  align="center" width="350px" >
                        <slot slot-scope="scope">
                            <el-button size="mini" @click="viewDetail(scope.row)">查看</el-button>
							<el-button size="mini" type="primary" @click="onEdit(scope.row)" v-pms="'userEdit'">编辑</el-button>
							<el-button class="btn" type="danger" size="mini" @click="onDelete(scope.row)"  v-pms="'userDelete'">删除</el-button>
							<el-button class="btn" type="warning" size="mini" @click="onResetPsw(scope.row)" title="点击重置密码为123456" v-pms="'userEdit'">重置密码</el-button>
						</slot>
                    </el-table-column>
                </el-table>
            </div>
            <el-pagination layout="prev, pager, next"
                :current-page="listData.pageNum"
                :page-size="listData.pageSize"
                :total="listData.total"
                @current-change="getList"
                @prev-click="getList"
                @next-click="getList"
            ></el-pagination>
        </div>
		<!-- 部门-区域树选择面板 -->
		<el-dialog class="tree-dialog" width="30%" :title="tree.treeTitle" :visible.sync="tree.showTreeDialog" append-to-body>
		    <el-tree  :data="tree.treeData" show-checkbox check-strictly node-key="id"  ref="eltree" @check="onNodeCheked"></el-tree>
		    <div class="button-bar">
		        <el-button @click="onCancelTree">取 消</el-button>
		        <el-button type="primary" @click="onConfirmTree">确 定</el-button>
		    </div>
		</el-dialog>
		<el-dialog :title="optType" :visible.sync="showDialog">
		  <component
		  v-bind:is="curComponent"
		  :rowId="rowId"
		  :userStatusList="userStatusList"
		  :roleList="roleList"
		  @closeDialog="closeDialog"
		  @refresh="getList(1)"
		  ></component>
		</el-dialog>
    </div>
</template>
<script>
import treeMinxin from "@/components/tree/tree.mixin.js"
import Md5 from 'js-md5'
import edit from "./user-edit.vue";
import detail from "./user-detail.vue";
export default{
    mixins:[treeMinxin],
	components: { edit, detail },
    data(){
        return{
            listData:{
                pageNum:1,//页码
                pageSize:25,
                total:5,//总共条数
                data:[]
            },
            filter: {
                name:'',
                account: '',
                phone:'',
                roleIds:'',
            },
            selected:[],
            roleList:[],//角色列表
			userStatusList:[],
			curComponent: "edit", //detail，edit
			showDialog:false,
			optType: "编辑", //新增/编辑/详情
			rowId:"",
        }
    },
   watch:{
     showDialog(vv){
		 if(!vv){
			 this.rowId=""
		 }
     }
   },
    methods:{
        getList(pageNum){
            if(this.$refs.listData){
                this.selected=[];
                this.$refs.listData.clearSelection();
            }
            var submitData={
                current:typeof pageNum=='number' ? pageNum : this.listData.pageNum,
                size:this.listData.pageSize,
                areaId:this.tree.districtNodeChecked.id,
                deptId:this.tree.deptNodeChecked.id,
                ...this.filter,
            };

            this.$http.getUserList(submitData)
            .then((res)=>{
                var res=res.data.data;
                if(!res){
                    return
                }
                this.$set(this.listData,'pageNum',res.current);
                this.$set(this.listData,'pageSize',res.size);
                this.$set(this.listData,'total',res.total);
                //var newData=this.transData(res.records)
                this.$set(this.listData,'data',res.records)

            }).catch((err)=>{
                if(err.data && err.data.message){

                }else{
                    window.message.close()
                    window.message= this.$message({
                        type:'error',
                        message:'程序出错,查询失败!',
                        showClose:true,
                    })
                }
                throw(err)
            })
            this.$store.commit('setUserDetail',{})
        },

        //添加用户
        onAdd(){
            // this.selected=[];
            // this.$refs.listData.clearSelection();
            // this.$router.push({path: "/sys/user-edit"});
            // this.$store.commit('setUserDetail',null)
			this.$refs.listData.clearSelection();
			this.optType = "新增";
			this.showDialog = true;
			this.curComponent=edit
			this.$nextTick(()=>{
			  this.checked = [];
			  this.rowId=""
			})
        },
		
		onEdit(rowData){
			this.curComponent=edit
			this.optType = "编辑";
			this.showDialog = true;
			this.$nextTick(()=>{
			  this.rowId=rowData.id
			})
		},

        //删除用户
        onDelete(rowData){
			this.$confirm('请确认是否删除?', '警告', {
			   confirmButtonText: '确定',
			   cancelButtonText: '取消',
			   type: 'warning'
			 }).then(() => {
					var submitData={userId:rowData.id}
					this.$http.deleteUser(submitData)
					.then((res)=>{
					    this.$message.success("删除成功!")
					    this.getList()//重新加载列表
					}).catch((err)=>{
					
					})
			 })
        },

        viewDetail(rowData){
            // this.$router.push({
            //     path:'/sys/user-detail',
            //     query:{id:rowData.row.id}
            // })
			
			this.curComponent=detail
			this.optType = "查看详情";
			this.showDialog = true;
			this.$nextTick(()=>{
			  this.rowId=rowData.id
			})
        },


        //全选
        onSelectAll(selection){
            this.selected=selection
        },
        //选择
        onSelect(selection,row){
            this.selected=selection
        },

        closeDialog(bool){
            this.showDialog=bool
        },

        resetForm(){
            this.$refs.filter.resetFields()
            this.$set(this.tree,'deptNodeChecked',{label:'',id:''})
            this.$set(this.tree,'districtNodeChecked',{label:'',id:''})
            this.getList()
        },

        //查询所有角色
        getAllRoleList(){
            var promise=new Promise((resolve,reject)=>{
                this.$http.getAllRoleList()
                .then((res)=>{
                    this.roleList=res.data.data
                    resolve(res)
                }).catch((err)=>{
                    reject(err)
                    throw(err)
                })
            })
            return promise

        },

        //  数据转换
        transData(data){
            if(!data || !Array.isArray(data)){
                return data
            }
            var newData=data.map((item)=>{
                    var rolelist=this.roleList.filter((role)=>{
                        if(!item.roleIds){return false}
                        return item.roleIds.split(',').indexOf(role.id)!=-1
                    })
                    item.roleIds=item.roleIds ? [...item.roleIds.split(',')] :[]
                    item.roleNames=rolelist.map((item)=>{
                        return item.name
                    }).join()
                    //状态识别
                    for(var key in this.userStatusList){
                        if(item.status===this.userStatusList[key]){
                            item.status=key
                        }
                    }

                    return item
            })
            return newData
        },

        onResetPsw(rowData){
            // if(this.selected.length==0){
            //     this.$message.warning("请选择一个用户!")
            //     return
            // }else if(this.selected.length>1){
            //     this.$message.warning("只能选择一个用户!")
            //     return
            // }
            var submitData={
                id:rowData.id,
                password:Md5("123456"),
                moduleName:'用户管理',
            }
            this.$http.resetPsw(submitData)
            .then((res)=>{
                this.$message.success("重置密码成功!")
            }).catch((err)=>{
                if(err.data && err.data.message){

                }else{
                    window.message.close()
                    window.message= this.$message({
                        type:'error',
                        message:'程序出错,操作失败!',
                        showClose:true,
                    })
                }
                throw(err)
            })
        },
		
		//查询用户状态
		getUserStatusList() {
		    this.$http.getDictKeyList({parentCode:'status'})
		    .then(res => {
		      let data = res.data.data;
		      this.userStatusList = data ||[];
		    }).catch(err => {
		      throw(err);
		    });
		},
		
		//查询所有角色
		getAllRoleList() {
		    this.$http.getRoleList()
		    .then(res => {
		      let data = res.data.data;
		      this.roleList = data;
		    }).catch(err => {
		      throw(err);
		    });
		},
		
		closeDialog() {
		  this.showDialog = false;
		},

    },

    async created(){
       // await this.getAllRoleList()
	   this.getUserStatusList()
	   this.getAllRoleList()
        this.getList()
    },


}
</script>

